<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiTrainingDatasetCategoriesApi } from '#/api/ai/dataset/trainingDatasetCategories';

import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { downloadFileFromBlobPart } from '@vben/utils';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteTrainingDatasetCategories,
  exportTrainingDatasetCategories,
  getTrainingDatasetCategoriesList,
} from '#/api/ai/dataset/trainingDatasetCategories';
import { ColorPicker } from '#/components/color-picker';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Detail from './modules/detail.vue';
import Form from './modules/form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: Detail,
  destroyOnClose: true,
});

/** 切换树形展开/收缩状态 */
const isExpanded = ref(true);
function handleExpand() {
  isExpanded.value = !isExpanded.value;
  gridApi.grid.setAllTreeExpand(isExpanded.value);
}

/** 刷新表格 */
function handleRefresh() {
  gridApi.query();
}

/** 创建数据集分类 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑数据集分类 */
function handleEdit(
  row: AiTrainingDatasetCategoriesApi.TrainingDatasetCategories,
) {
  formModalApi.setData(row).open();
}

/** 查看数据集分类 */
function handleDetail(
  row: AiTrainingDatasetCategoriesApi.TrainingDatasetCategories,
) {
  detailModalApi.setData(row).open();
}

/** 新增下级数据集分类 */
function handleAppend(
  row: AiTrainingDatasetCategoriesApi.TrainingDatasetCategories,
) {
  formModalApi.setData({ parentId: row.id }).open();
}

/** 删除数据集分类 */
async function handleDelete(
  row: AiTrainingDatasetCategoriesApi.TrainingDatasetCategories,
) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    duration: 0,
  });
  try {
    await deleteTrainingDatasetCategories(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.name]),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 导出表格 */
async function handleExport() {
  const data = await exportTrainingDatasetCategories();
  downloadFileFromBlobPart({ fileName: '数据集分类.xls', source: data });
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    id: 'TrainingDatasetCategories-grid',
    columns: useGridColumns(),
    height: 'auto',
    treeConfig: {
      parentField: 'parentId',
      rowField: 'id',
      transform: true,
      expandAll: true,
      reserve: true,
    },
    pagerConfig: {
      enabled: false,
    },
    proxyConfig: {
      ajax: {
        query: async (_, formValues) => {
          return await getTrainingDatasetCategoriesList(formValues);
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
      slots: {
        tools: 'toolbar-tools',
      },
    },
  } as VxeTableGridOptions<AiTrainingDatasetCategoriesApi.TrainingDatasetCategories>,
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <DetailModal @success="handleRefresh" />
    <Grid table-title="数据集分类列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: isExpanded ? '收缩' : '展开',
              type: 'primary',
              onClick: handleExpand,
            },
            {
              label: $t('ui.actionTitle.create', ['数据集分类']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['ai:training-dataset-categories:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['ai:training-dataset-categories:export'],
              onClick: handleExport,
            },
          ]"
        />
      </template>

      <template #icon="{ row }">
        <IconifyIcon :icon="row.icon" :color="row.color" />
      </template>
      <template #color="{ row }">
        <ColorPicker v-model="row.color" :disabled="true" />
      </template>

      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '新增下级',
              type: 'link',
              icon: ACTION_ICON.ADD,
              auth: ['ai:training-dataset-categories:create'],
              onClick: handleAppend.bind(null, row),
            },
            {
              label: '查看',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['ai:training-dataset-categories:query'],
              onClick: handleDetail.bind(null, row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['ai:training-dataset-categories:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['ai:training-dataset-categories:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.name]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
